package yartiss.engine.simulation.system;

import yartiss.engine.simulation.system.schedulable.Job;


public class ExecutionManager {
	
	
	/**
	 * simulate the fact this task has been executed during elapsedTime tu. This
	 * has effects on the current task job and on the simulator energy level.
	 * 
	 * @param elapsedTime
	 * @return the energy consumed
	 */
	public long execute(ITask task ,long elapsedTime) {
		assert task.isActive();
		return execute(task, task.getCurrentJob(), elapsedTime);
	}
	
	private long execute(ITask task, Job job,  long duration) {

		assert duration >= 0;

		if (duration == 0) {
			task.setLastExecutedJob(job);
			return 0;
		}

		// Time
		job.consumeProcTime(duration);
		if (job.getRomainingTimeCost() == 0) {
			task.getActiveJobs().poll();
		}
		task.setLastExecutedJob(job);

		// Energy
		long consumed = task.getEnergyConsumption(duration);

		assert consumed * task.getWcet() == duration * task.getWcee() : "wcee not divisible by wcet";
		job.consumeEnergy(consumed);

		assert job.getRomainingEnergyCost() >= 0 : "date : "+task.getId() + " has consumed more energy than wcee";
		assert job.getRomainingTimeCost() >= 0 : task.getId() + " has consumed more time than wcet";

		return consumed;
	}
	
	
	
	


}
